package com.zhouyilin.bigevent2.controller;


import com.zhouyilin.bigevent2.pojo.Result;
import com.zhouyilin.bigevent2.pojo.User;
import com.zhouyilin.bigevent2.service.UserService;
import com.zhouyilin.bigevent2.utils.JwtUtil;
import com.zhouyilin.bigevent2.utils.Md5Util;
import com.zhouyilin.bigevent2.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import lombok.val;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {


    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{3,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password) {
//        参数校验

//            查询用户
            User u = userService.findByUserName(username);
            if (u == null) {
//            为空 进行注册
//
                userService.register(username,password);
                return Result.success();
            }else {
                return Result.error("用户名已存在");
            }
    }

    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{3,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password){
        User loginUser = userService.findByUserName(username);
        if (loginUser == null) {
            return Result.error("用户不存在");
        }else {
            if (Md5Util.checkPassword(password, loginUser.getPassword())) {
                Map<String ,Object> claims = new HashMap<>();
                claims.put("id",loginUser.getId());
                claims.put("username",loginUser.getUsername());
                String token = JwtUtil.genToken(claims);

//                把token存储到redis中
                ValueOperations<String ,String> ops = stringRedisTemplate.opsForValue();
                ops.set(token,token,1, TimeUnit.HOURS);
                return Result.success(token);
            }else {
                return Result.error("密码错误，请重试");
            }
        }
    }

    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization") String token*/) {
        Map <String ,Object > map   = ThreadLocalUtil.get();
        String username = (String) map.get("username");
//        Map<String , Object> map = JwtUtil.parseToken(token);
//        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){
        userService.update(user);
        return Result.success();
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> params,@RequestHeader("Authorization") String token){
    //      校验参数
        String old_pwd =params.get("old_pwd");
        String new_pwd =params.get("new_pwd");
        String re_pwd =params.get("re_pwd");
        if (!StringUtils.hasLength(old_pwd) || !StringUtils.hasLength(new_pwd) || !StringUtils.hasLength(re_pwd)){
            return Result.error("缺少必要的参数1");
        }
//        校验原密码是否正确
        Map<String,Object> map   = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = userService.findByUserName(username);
        if (! Md5Util.checkPassword(old_pwd,loginUser.getPassword())){
            return Result.error("密码错误！");
        }
        if(!re_pwd.equals(new_pwd)){
            return Result.error("两次填写的密码不一致！");
        }
//        调用userService修改密码
        userService.updatePwd(new_pwd);

//        删除redis中对应的token
        ValueOperations<String,String> ops = stringRedisTemplate.opsForValue();
        ops.getOperations().delete(token);
        return Result.success();
    }
}
